import java.util.*;
import java.io.*;
import java.math.*;
import java.util.concurrent.*;

public class Example {
    static List<Integer> list = Collections.synchronizedList(new ArrayList<>());

    public static void main(String args[]) {
        Thread addThread = new Thread(new AddTask());
        Thread iteThread = new Thread(new iterateTask());

        addThread.start();
        iteThread.start();
    }

}

class AddTask implements Runnable {
    public void run() {
        try {
            for (int i = 1; i <= 100; i++) {
                Example.list.add(i); //SynchronizedList的add方法是同步的，无需再增加同步块
                Thread.sleep(10);
            }
        }
        catch (InterruptedException ex) {
            ex.printStackTrace();
        }
    }
}

class iterateTask implements Runnable {
    public void run() {
        for (int i = 1; i <= 10; i++) {
            try {
                synchronized (Example.list) {
                    Iterator<Integer> ite = Example.list.iterator();
                    while (ite.hasNext()) {
                        System.out.print(ite.next() + " ");
                        Thread.sleep(10);
                    }
                }
                System.out.println();
                Thread.sleep(100);
            }
            catch (InterruptedException ex) {
                ex.printStackTrace();
            }
            catch (ConcurrentModificationException ex) {
                ex.printStackTrace();
            }
        }
    }
}